import { createRouter, createWebHistory } from "vue-router";

import LoginVue from '../views/Login.vue'
import LitchiMap from '../views/litchi/LitchiMap.vue'
import UserLayout from '../views/layout/UserLayout.vue'
import LitchiMain from '../views/litchi/LitchiMain.vue'
import LitchiType from '../views/litchi/LitchiType.vue'
import LitchiRegion from '../views/litchi/LitchiRegion.vue'
import CommentVue from '../views/comment/Comment.vue'
import { useUserPermissionStore } from '@/stores/userpermission'
//定义路由关系
const routes = [
    {
        path: '/login',
        name: 'login',
        component: LoginVue
    },
    {
        path: '/',
        name: 'userLayout',
        component: UserLayout,
        redirect: '/user/litchiMain',

        children: [
            {
                path: '/user/litchiMap',
                name: 'litchiMap',
                component: LitchiMap
            },

            {
                path: '/user/litchiMain',
                name: 'litchiMain',
                component: LitchiMain
            },
            {
                path: '/user/litchiType',
                name: 'litchiType',
                component: LitchiType
            },

            {
                meta: {
                    requiresAuth: true,
                    allowedRoles: ['admin']
                },
                path: '/user/comment',
                name: 'comment',
                component: CommentVue

            }

        ]
    },

    {
        path: '/city-detail',
        name: 'CityDetail',
        component: LitchiRegion,
        props: route => ({
            city: decodeURIComponent(route.query.city),
            production: Number(route.query.production)
        })
    }



]


//创建路由实例
const router = createRouter({
    history: createWebHistory(),
    routes
})

// 在路由配置中添加导航守卫调试
// 修改现有的导航守卫
router.beforeEach(async (to, from, next) => {
  console.log('Navigating to:', to.path)
  
  const userPermission = useUserPermissionStore()
  
  // 检查路由是否需要认证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 检查用户权限
    if (to.matched.some(record => record.meta.allowedRoles)) {
      const hasRequiredRole = to.meta.allowedRoles.some(role => 
        userPermission.hasPermission(role)
      )
      
      if (!hasRequiredRole) {
        // 没有权限的处理方式
        Element.message.error('无权限访问')
        connsole.log('No permission')
        next('/login') // 或跳转到无权限页面
        return
      }
    }
    
    
  }
  
  next()
})

//导出路由
export default router